//
//  BCProjectDetailsBottomView.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/23.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "BCProjectDetailsBottomView.h"

#import "BCProjectDetailResponse.h"

#import "BCTimerHandler.h"
#import "NSDate+BCustom.h"

@interface BCProjectDetailsBottomCountdownView ()

@property (nonatomic, strong) QMUILabel *countdownLabel;

@end

@implementation BCProjectDetailsBottomCountdownView

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.countdownLabel = [QMUILabel new];
        self.countdownLabel.textColor = [UIColor qmui_colorWithHexString:@"#333333"];
        self.countdownLabel.font = [self.class countdownFont];
        self.countdownLabel.textAlignment = NSTextAlignmentCenter;
        self.countdownLabel.numberOfLines = 2;
        [self addSubview:self.countdownLabel];
        [self.countdownLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.centerY.mas_equalTo(self);
            make.width.mas_equalTo(self).offset(-20.0);
            make.height.mas_equalTo(self);
        }];
    }
    return self;
}

+ (UIFont *)countdownFont {
    return [UIFont systemFontOfSize:10 weight:UIFontWeightRegular];
}

+ (CGFloat)defaultHeight {
    return [self countdownFont].lineHeight*2+1;
}

@end


@interface BCProjectDetailsBottomView () <BCTimerHandlerDelegate> {
    BOOL _needTimerHandler;
}

@property (nonatomic, strong) BCBottomButton *mainButton;

/**
 *preButton
 */
@property (nonatomic, strong) BCBottomButton *preButton;


/**
 *BCTimerHandler 管理倒计时
 */
@property (nonatomic, strong) BCTimerHandler *timerHandler;

@end

@implementation BCProjectDetailsBottomView

- (BCTimerHandler *)timerHandler {
    if (!_timerHandler) {
        _timerHandler = [BCTimerHandler new];
        _timerHandler.delegate = self;
    }
    return _timerHandler;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
//        self.backgroundColor = [UIColor clearColor];
        [self setupSubviews];
    }
    return self;
}

- (void)setupSubviews {
    self.mainButton = [BCBottomButton new];
    self.mainButton.adjustsButtonWhenDisabled = false;
    [self addSubview:self.mainButton];
    [self.mainButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.top.mas_equalTo(self);
        make.left.mas_equalTo(self).offset(0);
    }];
    self.mainButton.backgroundColor = [UIColor darkMainColor];
    self.mainButton.displayButton.titleLabel.numberOfLines = 0;
    self.mainButton.displayButton.titleEdgeInsets = UIEdgeInsetsMake(0, 3, 0, 3);
    self.mainButton.displayButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    //
    self.preButton = [BCBottomButton new];
    self.preButton.adjustsImageWhenDisabled = false;
    self.preButton.backgroundColor = [UIColor darkSubMainColor];
    [self addSubview:self.preButton];
    [self.preButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.bottom.mas_equalTo(self);
        make.right.mas_equalTo(self.mainButton.mas_left);
    }];
    self.preButton.displayButton.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
    self.preButton.displayButton.titleLabel.numberOfLines = 0;
    self.preButton.displayButton.titleLabel.adjustsFontSizeToFitWidth = true;
    self.preButton.displayButton.titleEdgeInsets = UIEdgeInsetsMake(0, 3, 0, 3);
    self.preButton.displayButton.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    //
    self.countdownView = [BCProjectDetailsBottomCountdownView new];
    [self addSubview:self.countdownView];
    [self.countdownView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self);
        make.bottom.mas_equalTo(self.mas_top);
        make.width.mas_equalTo(self);
        make.height.mas_equalTo([BCProjectDetailsBottomCountdownView defaultHeight]);
    }];
}

#pragma mark - BCTimerHandlerDelegate
- (void)timerHandlerRepeatsAction {
    self.countdownView.countdownLabel.text = [self lastTimeString:self.projectData];
}

- (void)setProjectData:(BCProjectDetailData *)projectData {
    _projectData = projectData;
    //
    _needTimerHandler = false;//设置时默认不需要
    self.countdownView.alpha = 0;
    //移除target
    [self.mainButton removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    [self.preButton removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    //
    if (projectData) {
        self.alpha = 1;
        //根据状态显示不同操作
        [self loadViews:projectData];
    }else {
        self.alpha = 0;
    }
    if (_needTimerHandler) {
        self.countdownView.alpha = 1;
        [self timerHandlerRepeatsAction];
        [self.timerHandler start];
    }else {
        [self.timerHandler stop];
    }
}
- (void)loadViews:(BCProjectDetailData *)data {
    //设置开始时默认不开启手势接受 需要状态自行开启
    self.mainButton.userInteractionEnabled = false;
    self.preButton.userInteractionEnabled = false;
    if (self.isPreBuy) {//预购界面
        [self handlePreBuy:data];
    }else {
        //当前购买界面
        //当前项目状态
        BCProjectDetailStatus status = data.data.sub_status;
        switch (status) {
            case BCProjectDetailStatus_0://未开始
            {
                [self setNotStart:data];
            }
                break;
            case BCProjectDetailStatus_1://进行中
            {
                _needTimerHandler = true;
                [self setOngoing:data];
            }
                break;
            case BCProjectDetailStatus_2://募集成功
            {
                _needTimerHandler = true;
                [self setSuccess:data];
            }
                break;
            case BCProjectDetailStatus_3://下一轮筹集成功，本轮正在结算发放
            {
                [self setSuccess:data];
            }
                break;
            case BCProjectDetailStatus_4://下一轮筹集失败 本轮正在结算发放
            {
                [self setSuccess:data];
            }
                break;
            case BCProjectDetailStatus_5://下一轮筹集成功，本轮发放完毕
            {
                [self setSuccess:data];
            }
                break;
            case BCProjectDetailStatus_6://下一轮筹集失败，本轮退还完毕
            {
                [self setSuccess:data];
            }
                break;
            case BCProjectDetailStatus_7://本轮募集失败
            {
                [self setFailure:data];
            }
                break;
            default:
            {//其他未知状态 隐藏视图
                self.alpha = 0;
            }
                break;
        }
    }
}
/**
 通用
 */
- (UIFont *)normalTitleFont {
    return [UIFont systemFontOfSize:15 weight:UIFontWeightRegular];
}
- (UIFont *)mediumTitleFont {
    return [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
}
- (UIFont *)smallFont {
    return [UIFont systemFontOfSize:10 weight:UIFontWeightRegular];
}
- (UIColor *)normalTitleColor {
    return [UIColor whiteColor];
}
#pragma mark - 当前轮购买
/**
 设置活动未开始状态
 */
- (void)setNotStart:(BCProjectDetailData *)data {
    NSString *title = data.flow.status_str.not_start;
    NSAttributedString *attri = [[NSAttributedString alloc] initWithString:title attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
    [self.mainButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
    //
    [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(0);
    }];
}
/**
 设置活动进行中
 */
- (void)setOngoing:(BCProjectDetailData *)data {
    //判断是否已经购买
    if (data.data.is_buy) {
        [self setOngoingIsBuy:data];
    }else {//显示立即购买
        self.mainButton.userInteractionEnabled = true;//可以点击
        //
        NSString *string = data.flow.status_str.not_buy;
//        NSString *subString = [self lastTimeString:data];
        //
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
        //
        [self.mainButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
        //需要
        [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(0);
        }];
        //添加立即购买target
        [self.mainButton addTarget:self action:@selector(toBuyNowAction) forControlEvents:UIControlEventTouchUpInside];
    }
}
//设置活动进行中但是已经购买
- (void)setOngoingIsBuy:(BCProjectDetailData *)data {
    //已经购买了 需要判断是否可以预购 或者已经预购了
    //判断是否可以预购
    if (!data.data.has_next_buy) {//不可预购
        NSString *string = data.flow.status_str.succ_buy;
//        NSString *subString = [self lastTimeString:data];
        //
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
//        if (subString.length) {
//            subString = [NSString stringWithFormat:@"\n%@",subString];
//            NSAttributedString *subAttri = [[NSAttributedString alloc] initWithString:subString attributes:@{NSFontAttributeName:[self normalTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
//            [attri appendAttributedString:subAttri];
//        }
        //
        [self.mainButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
        //
        [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(0);
        }];
    }else {//可以预购
        NSString *string = data.flow.status_str.succ_buy;
        //
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
        //
        [self.mainButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
        //
        if (data.data.is_next_buy) {//已经预购
            [self.preButton.displayButton setTitle:data.flow.status_str.all_buy forState:UIControlStateNormal];
            self.preButton.userInteractionEnabled = false;
        }else {
            [self.preButton.displayButton setTitle:data.flow.status_str.buy_next forState:UIControlStateNormal];
            self.preButton.userInteractionEnabled = true;
        }
        //
        CGFloat offset = ScreenWidth*(125.0/375.0);
        [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(offset);
        }];
        //添加预购target
        [self.preButton addTarget:self action:@selector(toPreBuyAction) forControlEvents:UIControlEventTouchUpInside];
    }
}
/**
 获取结束剩余时间 字符串
 */
- (NSString *)lastTimeString:(BCProjectDetailData *)data {
    NSDate *date = [BCServiceTimestampManager shared].date;
    NSDate *endTime = [NSDate stringToDate: data.data.end_time format:FullDateFormateString];
    NSString *timeLastString = [NSDate countdownStringBetweenDate:date endDate:endTime];
    return [NSString stringWithFormat:@"%@ %@",data.flow.status_str.the_end,timeLastString];
}

/**
 设置已经募集成功
 */
- (void)setSuccess:(BCProjectDetailData *)data {
    NSString *success = data.flow.status_str.success;
    //判断是否已经购买和是否可预购下一轮
    if (data.data.is_buy)  {
        NSMutableAttributedString *attri = [[NSMutableAttributedString alloc] initWithString:success attributes:@{NSFontAttributeName:[self normalTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
        NSString *string = data.flow.status_str.succ_buy;
        NSString *subString = string;
        subString = [NSString stringWithFormat:@"\n%@",subString];
        NSAttributedString *subAttri = [[NSAttributedString alloc] initWithString:subString attributes:@{NSFontAttributeName:[self smallFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
        [attri appendAttributedString:subAttri];
        [self.mainButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
        //
        if (!data.data.has_next_buy) {//不可预购
            [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self).offset(0);
            }];
        }else {
            //可以预购要处理
            if (data.data.is_next_buy) {//已经预购
                [self.preButton.displayButton setTitle:data.flow.status_str.all_buy forState:UIControlStateNormal];
                self.preButton.userInteractionEnabled = false;
            }else {
                [self.preButton.displayButton setTitle:data.flow.status_str.buy_next forState:UIControlStateNormal];
                self.preButton.userInteractionEnabled = true;
                //添加预购target
                [self.preButton addTarget:self action:@selector(toPreBuyAction) forControlEvents:UIControlEventTouchUpInside];
            }
            CGFloat offset = ScreenWidth*(125.0/375.0);
            [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(self).offset(offset);
            }];
        }
    }else {//如果没有购买也不可预购下一轮了
        NSAttributedString *attri = [[NSAttributedString alloc] initWithString:success attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
        [self.mainButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
        //
        [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self).offset(0);
        }];
    }
}
/**
 设置募集失败
 */
- (void)setFailure:(BCProjectDetailData *)data {
    NSString *success = data.flow.status_str.fail;
    NSAttributedString *attri = [[NSAttributedString alloc] initWithString:success attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
    [self.mainButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
    //
    [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(0);
    }];
    //
    self.mainButton.backgroundColor = [UIColor qmui_colorWithHexString:@"#C1C0C9"];
}
#pragma mark - 预购界面
- (void)handlePreBuy:(BCProjectDetailData *)data {
    BCProjectDetailStatus status = data.data.sub_status;
    if (status==BCProjectDetailStatus_0) {
        /**
         "next_not_pay": "該項目暫時不支持預購",  // max_buy = 0  已经卖光了
         "next_pay": "立即預購",    // is_buy = 0 && max_buy > 0
         "next_succ_pay": "您已預購成功", // is_buy = 1
         */
        if (data.data.is_buy) {
            NSString *nextSuccPay = data.flow.status_str.next_succ_pay;
            NSAttributedString *attri = [[NSAttributedString alloc] initWithString:nextSuccPay attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
            [self.preButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
        }else {
            CGFloat maxBuy = data.data.max_buy.floatValue;
            if (maxBuy<=0) {
                NSString *nextNotPay = data.flow.status_str.next_not_pay;
                NSAttributedString *attri = [[NSAttributedString alloc] initWithString:nextNotPay attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
                [self.preButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
            }else {
                NSString *nextPay = data.flow.status_str.next_pay;
                NSAttributedString *attri = [[NSAttributedString alloc] initWithString:nextPay attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
                [self.preButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
                //
                self.preButton.userInteractionEnabled = true;
                //
                [self.preButton addTarget:self action:@selector(toPreBuyNowAction) forControlEvents:UIControlEventTouchUpInside];
            }
        }
    }else {//"next_stop_pay": "該輪預購已經結束"    // sub_status > 0
        NSString *nextStopPay = data.flow.status_str.next_stop_pay;
        NSAttributedString *attri = [[NSAttributedString alloc] initWithString:nextStopPay attributes:@{NSFontAttributeName:[self mediumTitleFont],NSForegroundColorAttributeName:[self normalTitleColor]}];
        [self.preButton.displayButton setAttributedTitle:attri forState:UIControlStateNormal];
    }
    [self.mainButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self).offset(ScreenWidth);
    }];
}


#pragma mark - buttonActions
//立即购买
- (void)toBuyNowAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(projectDetailsBottomViewToBuyNowAction)]) {
        [self.delegate projectDetailsBottomViewToBuyNowAction];
    }
}
//点击预购下一轮
- (void)toPreBuyAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(projectDetailsBottomViewToPreBuyAction)]) {
        [self.delegate projectDetailsBottomViewToPreBuyAction];
    }
}
//立即预购
- (void)toPreBuyNowAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(projectDetailsBottomViewToPreBuyNowAction)]) {
        [self.delegate projectDetailsBottomViewToPreBuyNowAction];
    }
}

- (void)dealloc {
    if (_timerHandler) {
        [_timerHandler stop];
        _timerHandler = nil;
    }
}

+ (CGFloat)defaultHeight {
    return [BCBottomButton defaultHeight];
}

@end
